package it.i118.jindice.json;

import java.util.Enumeration;

/**
 * Created with IntelliJ IDEA.
 * User: sciovante
 * Date: 04/11/13
 * Time: 17.16
 */
public class JSONArray implements Enumeration {
    JSONTokener x;

    private final int length;
    public JSONArray(JSONTokener x) throws JSONException {
        this.x = x;
        if (x.nextClean() != '[') {
            throw x.syntaxError("A JSONArray text must start with '['");
        }

        length = ((Integer) x.nextValue()).intValue();
        readNext();
//        if (x.nextClean() != ']') {
//            x.back();
//
//        }
    }

    public int length() {
        return length;
    }

    private Object next;

    private void readNext() {
        char nextChar = x.nextClean();
        if(nextChar==']'){
            next = null;
        } else if (nextChar == ',') {
            next = x.nextValue();
        } else {
            throw x.syntaxError("Expected a ',' or ']'");
        }
    }

    @Override
    public boolean hasMoreElements() {
        return next != null;
    }

//    The value can be a Boolean, Double, Integer,    * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
    public Long nextLong(){
        try {
            return (Long) next;
        } finally {
            readNext();
        }
    }
    public Integer nextInteger(){
        try {
            return (Integer) next;
        } finally {
            readNext();
        }
    }

    public Double nextDouble(){
        try {
            return (Double) next;
        } finally {
            readNext();
        }
    }

    public Boolean nextBoolean(){
        try {
            return (Boolean) next;
        } finally {
            readNext();
        }
    }

    public String nextString(){

        try {
            return (String) next;
        } finally {
            readNext();
        }
    }

    @Override
    public Object nextElement() {
        try {
            return next;
        } finally {
            readNext();
        }
    }
}
